package tool;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import constant.ConfigConstants;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * Created by Intellij IDEA.
 * User:  老赵
 * Date:  2023/7/6
 */
public class Json {

    public static void openJsonStage() {
        Stage stature = new Stage();
        stature.setTitle("JSON格式化");
        stature.setFullScreen(ConfigConstants.FullScreen);

        Label jsonLabel = new Label("格式化前的 JSON:");
        TextArea jsonTextField = new TextArea();

        Button calculateButton = new Button("格式化");

        Label jsonLabelAfter = new Label("格式化后的 JSON:");
        TextArea jsonTextArea = new TextArea();
        jsonTextArea.setWrapText(true); // 自动换行
        jsonTextArea.setEditable(false); // 只读
        jsonTextArea.setMinWidth(500);
        jsonTextArea.setMinHeight(700);

        calculateButton.setOnAction(event -> {
            String json = jsonTextField.getText();
            if (json.isEmpty()) {
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setTitle("警告");
                alert.setHeaderText(null);
                alert.setContentText("请输入 JSON");
                alert.showAndWait();
                return;
            }
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                Object jsonObject = objectMapper.readValue(json, Object.class);
                String formattedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
                jsonTextArea.setText(formattedJson);
            } catch (JsonProcessingException e) {
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setTitle("警告");
                alert.setHeaderText(null);
                alert.setContentText(e.getMessage());
                alert.showAndWait();
            }
        });
        VBox root = new VBox(10);
        root.setPadding(new Insets(10));
        root.getChildren().addAll(jsonLabel, jsonTextField, calculateButton, jsonLabelAfter, jsonTextArea);
        Scene scene = new Scene(root, 500, 700);
        stature.setScene(scene);
        stature.show();
    }
}
